package com.hszl.blog.controller;

import com.hszl.blog.utils.QiniuUtils;
import com.hszl.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author: 胡爽
 * @date: 2022/6/7 9:12
 **/
@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private QiniuUtils qiniuUtils;

    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file){
        //1.获取文件原始名
        String originalFilename = file.getOriginalFilename();
        //2.防止文件重名问题
        String fileName = UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(originalFilename,".");
        //3.下载文件到七牛云服务器

        boolean upload = qiniuUtils.upload(file, fileName);
        if (upload){
            return Result.success(qiniuUtils.url + fileName);
        }
        return Result.fail(20003,"文件下载失败");
    }
}
